package com.example.travelsn;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.travelsn.homepage.AdminFragment;
import com.example.travelsn.homepage.HomeFragment;
import com.example.travelsn.homepage.RegisteOrLogin;
import com.example.travelsn.homepage.SellerFragment;
import com.example.travelsn.homepage.UserFragment;
import com.example.travelsn.navigate.ConnateGPS;
import com.google.android.material.navigation.NavigationView;
import com.luluteam.itestlib.apm.APMInstance;
import com.luluteam.itestlib.apm.leak.LeakUploadService;
import com.squareup.leakcanary.LeakCanary;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button button;
    private DrawerLayout mDrawerLayout;

    public String getIsLogin() {
        return isLogin;
    }

    public String isLogin=null;

    //标题栏部分变量
    // 底部菜单2个Linearlayout
    private LinearLayout LLHome;
    private LinearLayout LLMy;
    // 底部菜单2个ImageView
    private ImageView ivHome;
    private ImageView ivMy;
    // 底部菜单2个菜单标题
    private TextView tvHome;
    private TextView tvMy;
    // 4个Fragment
    private Fragment homeFragment;
    private Fragment userFragment;
    private Fragment sellerFragment;
    private Fragment adminFragment;
    //head
    private NavigationView navigationView;
    private static TextView subscriber;
    final Context context = this;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT>=23) {
            List mPermissionList = new ArrayList<>();
            String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};
            for (String permission : permissions) {
                if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                    mPermissionList.add(permission);
                }
            }
            if (mPermissionList.size() > 0) {
                ActivityCompat.requestPermissions(this, (String[]) mPermissionList.toArray(
                        new String[mPermissionList.size()]), 0);
            }
        }
        //以下三行为待加入代码
        APMInstance apmInstance = APMInstance.getInstance();	//得到单例对象
        apmInstance.setSendStrategy(APMInstance.SEND_INSTANTLY);	//选择上报策略
        apmInstance.start(getApplication());	//开始监控

        LeakCanary.refWatcher(this).listenerServiceClass( LeakUploadService.class).buildAndInstall();

        // 初始化控件
        initView();
        // 初始化底部按钮事件
        initEvent();
        // 初始化并设置当前Fragment
        initFragment(0);
        //侧滑菜单部分
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        NavigationView navigationView = findViewById(R.id.nav_view);
        mDrawerLayout = findViewById(R.id.drawer_layout);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_launcher_background);
        }
        navigationView.setCheckedItem(R.id.nav_us);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
                switch (menuItem.getItemId()) {            //获取Id
                    case R.id.nav_us:
                        new AlertDialog.Builder(context).setTitle("关于我们").setMessage("为了方便大家在出行与旅游过程中的餐饮需求与参观娱乐方面的需求，" +
                                "基于Android平台的通过百度地图API实现定位开发的本系统应需求而生。目前正在完善，更多功能敬请期待")
                                .show();
                        //Toast.makeText (this,"关于我们",Toast.LENGTH_LONG).show ();
                        break;
                    case R.id.nav_account:
                        if(getUserType() == 4){
                            Intent intent = new Intent(MainActivity.this, RegisteOrLogin.class);
                            startActivity(intent);
                            break;
                        }else {
                            Toast.makeText(MainActivity.this,"您已登录",Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case R.id.nav_setting:
                        Intent intent = new Intent(MainActivity.this, ConnateGPS.class);
                        startActivity(intent);
                        break;
                    case R.id.nav_exit:
                        //清除用户登录信息
                        SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.clear();
                        editor.commit();
                        Toast.makeText(MainActivity.this,"您已退出当前登录用户",Toast.LENGTH_SHORT).show();
                        break;
                }
                //mDrawerLayout.closeDrawers();
                return true;
            }
        });
    }


    private void initFragment(int index) {
        // 由于是引用了V4包下的Fragment，所以这里的管理器要用getSupportFragmentManager获取
        FragmentManager fragmentManager = getSupportFragmentManager();
        // 开启事务
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        // 隐藏所有Fragment
        hideFragment(transaction);
        switch (index) {
            case 0:
                if (homeFragment == null) {
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.fl_content, homeFragment);
                } else {
                    transaction.show(homeFragment);
                }
                break;
            case 1:
                if(userFragment == null){
                    userFragment = new UserFragment();
                    transaction.add(R.id.fl_content,userFragment);
                }else{
                    transaction.show(userFragment);
                }
                break;
            case 2:
                if(sellerFragment == null){
                    sellerFragment = new SellerFragment();
                    transaction.add(R.id.fl_content,sellerFragment);
                }else{
                    transaction.show(sellerFragment);
                }
                break;
            case 3:
                if(adminFragment == null){
                    adminFragment = new AdminFragment();
                    transaction.add(R.id.fl_content,adminFragment);
                }else{
                    transaction.show(adminFragment);
                }
                break;
            default:
                break;
        }
        // 提交事务
        transaction.commit();
    }

    //隐藏Fragment
    private void hideFragment(FragmentTransaction transaction) {
        if (homeFragment != null) {
            transaction.hide(homeFragment);
        }
        if (userFragment != null) {
            transaction.hide(userFragment);
        }
        if (adminFragment != null) {
            transaction.hide(adminFragment);
        }
        if (sellerFragment != null) {
            transaction.hide(sellerFragment);
        }
    }

    private void initEvent() {
        // 设置按钮监听
        LLHome.setOnClickListener((View.OnClickListener) this);
        LLMy.setOnClickListener((View.OnClickListener) this);
    }

    private void initView() {

        // 底部菜单2个Linearlayout
        this.LLHome = (LinearLayout) findViewById(R.id.ll_home);
        this.LLMy = (LinearLayout)findViewById(R.id.ll_my);

        // 底部菜单2个ImageView
        this.ivHome = (ImageView) findViewById(R.id.iv_home);
        this.ivMy = (ImageView) findViewById(R.id.iv_my);

        // 底部菜单2个菜单标题
        this.tvHome = (TextView) findViewById(R.id.tv_home);
        this.tvMy = (TextView) findViewById(R.id.tv_my);

        this.navigationView = (NavigationView) findViewById(R.id.nav_view);
        View header = navigationView.getHeaderView(0);
        subscriber = (TextView) header.findViewById(R.id.subscriber);


    }

    @Override
    public void onClick(View v) {
        // 在每次点击后将所有的底部按钮(ImageView,TextView)颜色改为灰色，然后根据点击着色
        restartBotton();
        subscriber.setText(getUserName());
        // ImageView和TetxView置为绿色，页面随之跳转
        switch (v.getId()) {
            case R.id.ll_home:
                ivHome.setImageResource(R.drawable.home);
                tvHome.setTextColor(0xff1B940A);
                initFragment(0);
                break;
            case R.id.ll_my:
                ivMy.setImageResource(R.drawable.wode);
                tvMy.setTextColor(0xff1B940A);
                int type = getUserType();
                initFragment(type);
                break;
            default:
                break;
        }
    }

    private void restartBotton() {
        // ImageView置为灰色
        ivHome.setImageResource(R.drawable.home);
        ivMy.setImageResource(R.drawable.wode);
        // TextView置为白色
        tvHome.setTextColor(0xffffffff);
        tvMy.setTextColor(0xffffffff);
    }
    /*
    获取登录用户类型
     */
    private int getUserType(){
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
        return sharedPreferences.getInt("type",4);
    }
    public String  getUserName(){
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo", Activity.MODE_PRIVATE);
        return sharedPreferences.getString("name","not logged");
    }
}
